<template>
  <div class="app-container">
    <div class="filter-container">
      <el-date-picker
        v-model="times"
        class="filter-item"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 250px;"
        type="daterange"
        value-format="yyyy-MM-dd"
      />
      <el-select
        v-model="listQuery.channelId"
        filterable
        clearable
        :filter-method="appdataFilter"
        placeholder="选择应用名称"
        style="width: 150px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      >
        <el-option
          v-for="(item, index) in authChanneloptions"
          :key="index"
          :label="item.authChannelName"
          :value="item.authChannelId"
        />
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
    </div>
    <el-table
      :data="authData"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column prop="id" label="编号" align="center" width="60">
      </el-table-column>
      <el-table-column prop="authChannelName" label="渠道" align="center">
      </el-table-column>
      <el-table-column prop="collisionNum" label="撞库量" align="center">
      </el-table-column>
      <el-table-column prop="collisionSuccessNum" label="成功量" align="center">
      </el-table-column>
      <el-table-column
        prop="insuranceApplyNum"
        label="机构进件量"
        align="center"
        min-width="100"
      >
      </el-table-column>
      <!-- <el-table-column
        prop="mineNum"
        label="自己结算量"
        align="center"
        min-width="100"
      >
      </el-table-column>
      <el-table-column
        prop="otherSideNum"
        label="给对方结算量"
        align="center"
        min-width="100"
      >
      </el-table-column> -->
      <el-table-column
        prop="apsapplyNum"
        label="APS推送量"
        align="center"
        min-width="100"
      >
      </el-table-column>
      <el-table-column
        prop="appUV"
        label="贷超唯一访问量"
        align="center"
        min-width="100"
      >
      </el-table-column>
      <el-table-column label="成本消耗" align="center" width="100">
        <template slot-scope="scope">
          <el-button type="text" @click="showCalculateConsumption(scope)">{{
            consumArr[scope.$index]
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="预估营收" align="center" width="100">
        <template slot-scope="scope">
          <el-button type="text" @click="showEstimatedrevenue(scope)">{{
            estimateArr[scope.$index]
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="预估ROI" align="center" width="100">
        <template slot-scope="scope">
          {{
            ['NaN', 'Infinity'].includes(
              roundNumber(
                (estimateArr[scope.$index] - consumArr[scope.$index]) /
                  consumArr[scope.$index],
                3
              )
            )
              ? '-'
              : roundNumber(
                  (estimateArr[scope.$index] - consumArr[scope.$index]) /
                    consumArr[scope.$index],
                  3
                )
          }}
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getAuthStatistics"
    />
    <!-- 计算消耗金额 -->
    <el-dialog
      title="计算消耗金额"
      :visible.sync="consumeVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="cost">
        <el-form-item label="渠道单价" :label-width="formLabelWidth">
          <el-input
            v-model="cost.channelPrice"
            style="width: 200px;"
          ></el-input>
        </el-form-item>
        <el-form-item label="授权量" :label-width="formLabelWidth">
          <el-input
            v-model="cost.empowerNum"
            autocomplete="off"
            style="width: 200px;"
          ></el-input>
        </el-form-item>
        <el-form-item label="消耗金额" :label-width="formLabelWidth">
          <el-input
            v-model="cost.costAmount"
            autocomplete="off"
            style="width: 200px;"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="consumeVisible = false">取 消</el-button>
        <el-button type="primary" @click="consumeVisible = false"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 计算预估营收 -->
    <el-dialog
      title="预估营收"
      center
      :visible.sync="revenueVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="revenue">
        <div class="demo-input-suffix">
          <div class="Calculate_name">
            机构：{{ revenue.applyNum * revenue.AvgIncome }}元
          </div>
          <el-form-item label="进件量:" :label-width="formLabelWidth">
            <template slot-scope="scope">
              <el-col :span="6">
                <el-input
                  v-model="revenue.applyNum"
                  style="width: 80%;"
                  autocomplete="off"
                ></el-input>
              </el-col>
              <el-col
                class="line"
                :span="2"
                style="font-weight: bolder;margin-left: 20px;"
              >
                平均单价:
              </el-col>
              <el-col :span="6">
                <el-input
                  v-model="revenue.AvgIncome"
                  autocomplete="off"
                  style="width: 80%;"
                ></el-input>
              </el-col>
            </template>
          </el-form-item>
        </div>
        <div class="demo-input-suffix">
          <div class="Calculate_name">
            APS：{{ revenue.APSApplyNum * revenue.APSPushIncome }}元
          </div>
          <el-form-item label="推送量:" :label-width="formLabelWidth">
            <el-col :span="6">
              <el-input
                v-model="revenue.APSApplyNum"
                autocomplete="off"
                style="width: 80%;"
              ></el-input>
            </el-col>
            <el-col
              class="line"
              :span="2"
              style="font-weight: bolder;margin-left: 20px;"
            >
              平均单价:
            </el-col>
            <el-col :span="6">
              <el-input
                v-model="revenue.APSPushIncome"
                autocomplete="off"
                style="width: 80%;"
              ></el-input>
            </el-col>
          </el-form-item>
        </div>

        <div class="demo-input-suffix">
          <div class="Calculate_name">
            贷超：{{ revenue.APPUV * revenue.APPClikeIncome }}元
          </div>
          <el-form-item label="点击量:" :label-width="formLabelWidth">
            <el-col :span="6">
              <el-input
                v-model="revenue.APPUV"
                autocomplete="off"
                style="width: 80%;"
              ></el-input>
            </el-col>
            <el-col
              class="line"
              :span="2"
              style="font-weight: bolder;margin-left: 20px;"
            >
              平均单价:
            </el-col>
            <el-col :span="6">
              <el-input
                v-model="revenue.APPClikeIncome"
                autocomplete="off"
                style="width: 80%;"
              ></el-input>
            </el-col>
          </el-form-item>
        </div>
        <div class="calculate_total">
          合计：<span style="color:rgb(0, 60, 255)">{{
            estimatedRevenue
          }}</span>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="revenueVisible = false">取 消</el-button>
        <el-button type="primary" @click="revenueVisible = false"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 计算预估ROI -->
    <el-dialog
      title="计算ROI"
      :visible.sync="CalculateROIForm"
      :close-on-click-modal="false"
    >
      <el-form :model="estimateROI">
        <template slot-scope="scope">
          <el-form-item label="预估营收" :label-width="formLabelWidth">
            <el-input
              v-model="estimateROI.consumeAmount"
              @input="CalculateWantROI(scope)"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="消耗金额" :label-width="formLabelWidth">
            <el-input
              v-model="revenueCalculateROI.Estimatedrevenue"
              autocomplete="off"
              @input="CalculateWantROI"
            ></el-input>
          </el-form-item>
          <el-form-item label="ROI" :label-width="formLabelWidth">
            <el-input v-model="estimateROI.ROI" autocomplete="off"></el-input>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="CalculateROIForm = false">取 消</el-button>
        <el-button type="primary" @click="CalculateROIForm = false"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import waves from '@/directive/waves'; // waves directive
import Pagination from '@/components/Pagination'; // secondary package based on el-pagination
import { getAuthChannel, getAuthStatistics } from '@/api/auth';
import { timestampToTimeYear } from '@/utils/index';

export default {
  name: 'AuthStatistics',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      total: 0,
      authData: [],
      listQuery: {
        current: 1,
        size: 10,
        startTime: '',
        endTime: '',
        channelId: ''
      },
      formLabelWidth: 100,
      consumeVisible: false, // 计算消耗金额表格
      revenueVisible: false, // 计算预估营收表格
      authChanneloptions: [],
      times: [],
      timeNow: [
        new Date(new Date().toLocaleDateString()).getTime(),
        new Date(new Date().toLocaleDateString()).getTime() +
          24 * 60 * 60 * 1000
      ],
      cost: {
        channelPrice: 30,
        empowerNum: '',
        costAmount: ''
      }, // 成本消耗
      revenue: {
        applyNum: '', // 机构进件量
        AvgIncome: 30, // 平均进件收益
        APSApplyNum: '', // APS推送量
        APSPushIncome: 20, // 单个推送收益
        APPUV: '', // 贷超唯一访问量
        APPClikeIncome: 3 // 单个点击收益
      }, // 预估营收
      estimatedRevenue: 0, // 预估营收总金额
      estimateROI: {
        consumeAmount: '', // 消耗金额
        revenue: '', // 预估营收
        ROI: '' // ROI
      },
      CalculateROIForm: false,
      consumArr: [],
      consumindex: '',
      estimateArr: [],
      estimatedindex: [],
      calculateROIArr: [],
      calculateROIIndex: ''
    };
  },
  watch: {
    revenue: {
      handler: function(newV, oldV) {
        this.estimatedRevenue =
          newV.applyNum * newV.AvgIncome +
          newV.APSApplyNum * newV.APSPushIncome +
          newV.APPUV * newV.APPClikeIncome;
        this.estimateArr[this.estimatedindex] = this.estimatedRevenue;
        this.$set(this.estimateArr, this.estimatedindex, this.estimatedRevenue);
      },
      deep: true,
      immediate: true
    },
    cost: {
      handler: function(newV, oldV) {
        this.cost.costAmount = this.cost.empowerNum * this.cost.channelPrice;
        this.consumArr[this.consumindex] = this.cost.costAmount;
        this.$set(this.consumArr, this.consumindex, this.cost.costAmount);
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getAuthChannel();
    this.times = [
      timestampToTimeYear(this.timeNow[0]),
      timestampToTimeYear(this.timeNow[1])
    ];
    this.listQuery.endTime = this.times[1];
    this.listQuery.startTime = this.times[0];
    this.getAuthStatistics();
  },
  methods: {
    async getAuthChannel() {
      const res = await getAuthChannel();
      res.data.data.forEach(item => {
        if (item.channel_name !== null) {
          this.authChanneloptions.push(item);
        }
      });
    },
    async getAuthStatistics() {
      if (this.times == null || this.times.length === 0) {
        this.listQuery.endTime = '';
        this.listQuery.startTime = '';
      } else {
        this.listQuery.endTime = this.times[1];
        this.listQuery.startTime = this.times[0];
      }
      const res = await getAuthStatistics(this.listQuery);
      this.authData = res.data.data.records;
      this.total = res.data.data.total;
      this.consumArr = [];
      this.estimateArr = [];
      this.calculateROIArr = [];
      this.authData.forEach(item => {
        item.amountSum = item.applyNum * this.cost.channelPrice;
        this.consumArr.push(item.amountSum);
        // 预估营收：进件量*平均进件收益+APS推送量*单个推送收益+贷超唯一访问量*单个点击收益
        item.estimatedAmount =
          item.collisionSuccessNum * this.revenue.AvgIncome +
          item.apsapplyNum * this.revenue.APSPushIncome +
          item.appUV * this.revenue.APPClikeIncome;
        this.estimateArr.push(item.estimatedAmount);
        item.roi = (item.estimatedAmount - item.amountSum) / item.amountSum;
        this.calculateROIArr.push(item.roi);
      });
    },
    handleFilter() {
      this.listQuery.current = 1;
      if (
        this.listQuery.channelId === undefined ||
        this.listQuery.channelId === ''
      ) {
        this.getAuthStatistics(this.listQuery);
      } else {
        this.authChanneloptions.forEach(item => {
          if (item.authChannelId === this.listQuery.channelId) {
            // this.listQuery.nickname = item.channel_name;
            this.getAuthStatistics(this.listQuery);
          }
        });
      }
      this.getAuthStatistics();
    },
    showCalculateConsumption(scope) {
      // this.cost.costAmount = '';
      this.cost.channelPrice = 30;
      this.consumeVisible = true;
      this.cost.empowerNum = scope.row.applyNum;
      this.consumindex = scope.$index;
      this.cost.costAmount = this.consumArr[scope.$index];
    },
    showEstimatedrevenue(scope) {
      this.revenue.applyNum = scope.row.applyNum;
      this.revenue.APSApplyNum = scope.row.apsapplyNum;
      this.revenue.APPUV = scope.row.appUV;
      // this.estimatedRevenue =
      //   this.revenue.applyNum * this.revenue.AvgIncome +
      //   this.revenue.APSApplyNum * this.revenue.APSPushIncome +
      //   this.revenue.APPUV * this.revenue.APPClikeIncome;
      this.estimatedindex = scope.$index;
      this.revenueVisible = true;
    },
    showCalculateROI(scope) {
      this.CalculateROIForm = true;
      this.estimateROI.consumeAmount = this.consumArr[scope.$index];
      this.revenueCalculateROI.Estimatedrevenue = this.estimateArr[
        scope.$index
      ];
      this.estimateROI.ROI = this.calculateROIArr[scope.$index];
      this.calculateROIIndex = scope.$index;
    }, // 计算ROI
    CalculateWantROI(scope) {
      this.estimateROI.ROI =
        (this.revenueCalculateROI.Estimatedrevenue -
          this.estimateROI.consumeAmount) /
        this.estimateROI.consumeAmount;
      this.$set(
        this.calculateROIArr,
        this.calculateROIIndex,
        this.estimateROI.ROI
      );
    },
    // 四舍五入
    roundNumber(number, decimalPlaces) {
      return Number(number).toFixed(decimalPlaces);
    }
  }
};
</script>
<style>
.demo-input-suffix {
  width: 800px;
  height: 100px;
}
.Calculate_name {
  margin-bottom: 20px;
  font-size: 14px;
  font-weight: bold;
}
.calculate_total {
  margin-top: 20px;
  font-size: 18px;
  font-weight: bold;
}
</style>
